package com.accp.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.accp.dao.UserDao;
import com.accp.info.UserInfo;

public class UserDaoImpl implements UserDao{

	public UserInfo login(String name, String pwd) {
		String sql="SELECT * FROM userinfo WHERE USERNAME=? AND PASSWORD=?";
		System.out.println("name="+name);
		System.out.println("pwd="+pwd);
		System.out.println("SQL="+sql);
		
		List<UserInfo> list=null;
		ResultSet rs=null;
		DB db=new DB();
		
		try {
			rs = db.query(sql, name, pwd);
			list = rsToList(rs);
			db.close(rs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(list!=null && list.size()==1){
			return list.get(0);
		}else{
			return null;
		}
	}

	private List<UserInfo> rsToList(ResultSet rs) throws SQLException {
		List<UserInfo> list=new ArrayList<UserInfo>();
		while(rs.next()){
			UserInfo u=new UserInfo();
			u.setEmail(rs.getString("email"));
			u.setPassword(rs.getString("password"));
			u.setUsername(rs.getString("username"));
			list.add(u);
		}
		return list;
	}

	public boolean addUser(UserInfo user) {
		String sql="INSERT INTO userinfo VALUES(?,?,?)";
		DB db=new DB();
		int n=0;
		try {
			n = db.update(sql, user.getUsername(),
					user.getPassword(),
					user.getEmail());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return n>0;
	}

	

}
